//
//  UIImage+MultiFormat.m
//  SDWebImage
//
//  Created by Olivier Poitrey on 07/06/13.
//  Copyright (c) 2013 Dailymotion. All rights reserved.
//

#import "UIImage+MultiFormat.h"
#import "UIImage+GIF.h"
#import "NSData+ImageContentType.h"

#ifdef SD_WEBP
#import "UIImage+WebP.h"
#endif

@implementation UIImage (MultiFormat)

+ (UIImage *)sd_imageWithData:(NSData *)data {
    UIImage *image;
    NSString *imageContentType = [NSData contentTypeForImageData:data];
    if ([imageContentType isEqualToString:@"image/gif"]) {
        image = [UIImage sd_animatedGIFWithData:data];
    }
#ifdef SD_WEBP
    else if ([imageContentType isEqualToString:@"image/webp"])
    {
        image = [UIImage sd_imageWithWebPData:data];
    }
#endif
    else {
        image = [[UIImage alloc] initWithData:data];
#pragma mark - 修改的部分
        
        if (data.length/512 > 512) {
            image = [self compressImageWith:image];
        }
//        if (image.size.width>1024 && image.size.height>1024) {
//            image = [self compressImageWith:image];
//        }

    }

    return image;
}

+(UIImage *)compressImageWith:(UIImage *)image
{
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = 256;
    float height = image.size.height/(image.size.width/width);
    
    float widthScale = imageWidth / width;
    float heightScale = imageHeight / height;
    
    //创建bitmap的context，并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth/heightScale, height)];
    }
    else
    {
        [image drawInRect:CGRectMake(0, 0, width, imageHeight/widthScale)];
    }
    
    //从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //使当前context出堆栈
    UIGraphicsEndImageContext();
    return newImage;
}

+(UIImage *)compressHeaderImageWith:(UIImage *)image
{
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = 128;
    float height = image.size.height/(image.size.width/width);
    
    float widthScale = imageWidth / width;
    float heightScale = imageHeight / height;
    
    //创建bitmap的context，并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth/heightScale, height)];
    }
    else
    {
        [image drawInRect:CGRectMake(0, 0, width, imageHeight/widthScale)];
    }
    
    //从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //使当前context出堆栈
    UIGraphicsEndImageContext();
    return newImage;
}






























@end
